// https://www.lintcode.com/problem/best-time-to-buy-and-sell-stock-ii

public class Solution {
    /**
     * @param prices: Given an integer array
     * @return: Maximum profit
     */
    public int maxProfit(int[] prices) {
        // write your code here
        int ret = 0;
        int buyPrice = -1;
        for (int i = 0; i < (prices.length - 1); ++i) {
          if (buyPrice == -1) { // 没有股票
            if (prices[i] < prices[i + 1]) { // 买
              buyPrice = prices[i];
            }
          } else {
            if (prices[i] > prices[i + 1]) { // 卖
              ret += prices[i] - buyPrice;
              buyPrice = -1;
            }
          }
        }
        if (buyPrice != -1) { // 卖掉手上剩的股票
          ret += prices[prices.length - 1] - buyPrice;
        }
        return ret;
    }
}